package com.gaga.console.core.controller.auth;


import cn.dev33.satoken.stp.StpUtil;
import com.gaga.common.enums.DeviceType;
import com.gaga.common.exception.CaptchaException;
import com.gaga.common.path.ApiPath;
import com.gaga.common.result.Result;
import com.gaga.console.base.controller.BaseController;
import com.gaga.console.base.entity.LoginBody;
import com.gaga.console.base.entity.SecretKeyLoginBody;
import com.gaga.console.core.service.AuthService;
import com.gaga.console.core.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;


/**
 * 认证
 *
 * @author liujia
 * @since 2022-05-19
 */
@Api(tags = "认证登录")
@RestController
@RequestMapping(ApiPath.ROOT + "/auth")
public class AuthController extends BaseController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private AuthService authService;

    /**
     * 登录
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody LoginBody loginBody) throws CaptchaException {

        boolean validateCode = true;
        if (StringUtils.isNotBlank(loginBody.getDeviceType()) && loginBody.getDeviceType().equals(DeviceType.TEST.getInfo())) {
            validateCode = false;
        }
        if (validateCode) {
            authService.check(loginBody.getUuid(), loginBody.getCode());
        }
        return sysUserService.login(loginBody.getUsername(), loginBody.getPassword());
    }

    @ApiOperation(value = "获取验证码")
    @GetMapping("/captcha")
    public Result captcha() {
        return authService.getCode();
    }

    /**
     * 获取用户信息
     */
    @ApiOperation(value = "获取用户信息")
    @GetMapping("/user")
    public Result user() {
        return sysUserService.getUserInfo();
    }

    /**
     * 获取权限信息
     */
    @ApiOperation(value = "获取权限信息")
    @GetMapping("/permission")
    public Result permission() {
        return Result.ok(sysUserService.getPermissionList());
    }

    /**
     * 退出
     */
    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public Result logout() {
        StpUtil.logout();
        return Result.ok("退出成功");
    }


    @ApiOperation(value = "通过秘钥登录")
    @PostMapping("/loginBySecretKey")
    public Result loginBySecretKey(@RequestBody @Valid SecretKeyLoginBody secretKeyLoginBody) {
        return sysUserService.loginBySecretKey(secretKeyLoginBody);
    }

    @ApiOperation(value = "获取秘钥信息")
    @PostMapping("/getSecretKeyInfo")
    public Result getSecretKeyInfo(@RequestBody @Valid SecretKeyLoginBody secretKeyLoginBody) {
        return sysUserService.getSecretKeyInfo(secretKeyLoginBody);
    }
}
